package com.yuelan.codelib.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.Display;
import android.view.View;

public class BitmapUtil {

	/**
	 * Role:放大和缩小图片<BR>
	 * Date:2012-4-12<BR>
	 * 
	 * @author ZHENSHI)peijiangping
	 */
	public static synchronized Bitmap scaleBitMap(Bitmap bitmap,
			float scaleWidth, float scaleHeight) {
		int bmpWidth = bitmap.getWidth();
		int bmpHeight = bitmap.getHeight();
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);// 放大和缩小比例
		bitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix,
				false);
		return bitmap;
	}

	/**
	 * 作用：从内存卡中读取bitmap对象<BR>
	 * 作者：peijiangping<BR>
	 * 日期：2012-9-28
	 */
	public static Bitmap readBitMapForSD(String filepath, int sx) {
		Bitmap bitmap = null;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inPreferredConfig = Bitmap.Config.RGB_565;
		opts.inPurgeable = true;
		opts.inInputShareable = true;
		opts.inSampleSize = sx;
		BufferedInputStream bis = null;
		ByteArrayOutputStream out = null;
		byte isBuffer[] = new byte[1024];
		try {
			FileInputStream fis = new FileInputStream(filepath);
			bis = new BufferedInputStream(fis, 1024 * 4);
			out = new ByteArrayOutputStream();
			int len = 0;
			while ((len = bis.read(isBuffer)) != -1) {
				out.write(isBuffer, 0, len);
			}
			out.close();
			bis.close();
		} catch (OutOfMemoryError e) {
			System.gc();
			return null;
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (out == null)
			return null;
		byte[] data = out.toByteArray();
		try {
			// bitmap = BitmapFactory.decodeFile(filepath, opts);
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
		} catch (OutOfMemoryError e) {
			bitmap.recycle();
			System.gc();
			System.runFinalization();
			bitmap = null;
		}
		return bitmap;
	}

	/**
	 * 作用：sc根据需求设置<BR>
	 * 作者：peijiangping<BR>
	 * 日期：2012-9-28
	 */
	public static Bitmap readBitmapForBig(String filepath, int sc) {
		BufferedInputStream bis = null;
		ByteArrayOutputStream out = null;
		byte isBuffer[] = new byte[1024];
		try {
			FileInputStream fis = new FileInputStream(filepath);
			bis = new BufferedInputStream(fis, 1024 * 4);
			out = new ByteArrayOutputStream();
			int len = 0;
			while ((len = bis.read(isBuffer)) != -1) {
				out.write(isBuffer, 0, len);
			}
			out.close();
			bis.close();
		} catch (OutOfMemoryError e) {
			System.gc();
			return null;
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (out == null)
			return null;
		byte[] data = out.toByteArray();
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, options);
		options.inJustDecodeBounds = false;
		if (sc != 0) {
			int be = (int) (options.outHeight / (float) sc);
			if (be <= 0) {
				be = 1;
			} else if (be > 16) {
				be = 16;
			}
			options.inSampleSize = be;
		}
		Bitmap bmp = null;
		try {
			bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options);
		} catch (OutOfMemoryError e) {
			if (bmp != null) {
				bmp.recycle();
			}
			System.gc();
			System.runFinalization();
			bmp = null;
		}
		return bmp;
	}

	/**
	 * 作用：根据id获取bitmap对象<BR>
	 * 作者：peijiangping<BR>
	 * 日期：2012-9-28
	 */
	public static Bitmap readBitMapForPJ(Context c, int resId, int sx) {
		Bitmap bitmap = null;
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inSampleSize = sx;
		// 获取资源图片
		InputStream is = c.getResources().openRawResource(resId);
		try {
			bitmap = BitmapFactory.decodeStream(is, null, opt);
		} catch (OutOfMemoryError e) {
			System.gc();
			bitmap = null;
		}
		return bitmap;
	}

	/**
	 * 作者: peijiangping<BR>
	 * 时间:2013-6-5上午10:49:35<BR>
	 * 功能:设置圆角图片<BR>
	 * 返回值:Bitmap<BR>
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 作者: peijiangping<BR>
	 * 时间:2013-6-5上午10:49:35<BR>
	 * 功能:设置圆角图片<BR>
	 * 返回值:Bitmap<BR>
	 * 参数：pixels--圆角半径，true--直角，false--圆角
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels, boolean lt,
			boolean rt, boolean lb, boolean rb) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Paint paint1 = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		paint1.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		paint1.setColor(0xaaaaaaaa);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		if (lt) {
			canvas.drawRect(0, 0, bitmap.getWidth() - pixels,
					bitmap.getHeight() - pixels, paint);
		}
		if (rt) {
			canvas.drawRect(pixels, 0, bitmap.getWidth(), bitmap.getHeight()
					- pixels, paint);
		}
		if (lb) {
			canvas.drawRect(0, pixels, bitmap.getWidth() - pixels,
					bitmap.getHeight(), paint);
		}
		if (rb) {
			canvas.drawRect(pixels, pixels, bitmap.getWidth(),
					bitmap.getHeight(), paint);
		}
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	public static Bitmap loadImageFromUrl(String url, int sc) {
		URL m;
		InputStream i = null;
		BufferedInputStream bis = null;
		ByteArrayOutputStream out = null;
		byte isBuffer[] = new byte[1024];
		if (url == null)
			return null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();

			bis = new BufferedInputStream(i, 1024 * 4);
			out = new ByteArrayOutputStream();
			int len = 0;
			while ((len = bis.read(isBuffer)) != -1) {
				out.write(isBuffer, 0, len);
			}
			out.close();
			bis.close();
		} catch (OutOfMemoryError e) {
			System.gc();
			return null;
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (out == null)
			return null;
		byte[] data = out.toByteArray();
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, options);
		options.inJustDecodeBounds = false;
		int be = (int) (options.outHeight / (float) sc);
		if (be <= 0) {
			be = 1;
		} else if (be > 3) {
			be = 3;
		}
		options.inSampleSize = be;
		Bitmap bmp = null;
		try {
			bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options); // 返回缩略图
		} catch (OutOfMemoryError e) {
			// TODO: handle exception
			System.gc();
			bmp = null;
		}
		return bmp;
	}

	/**
	 * 作者: peijiangping<BR>
	 * 时间:2013-6-20下午1:55:56<BR>
	 * 功能:获取屏幕截图<BR>
	 * 返回值:Bitmap<BR>
	 */
	public static Bitmap cutScreen(Activity c) {
		View view = c.getWindow().getDecorView();
		Display display = c.getWindowManager().getDefaultDisplay();
		view.layout(0, 0, display.getWidth(), display.getHeight());
		view.setDrawingCacheEnabled(true);// 允许当前窗口保存缓存信息，这样getDrawingCache()方法才会返回一个Bitmap
		return Bitmap.createBitmap(view.getDrawingCache());
	}

	/**
	 * 作者: peijiangping<BR>
	 * 时间:2013-6-20下午1:56:13<BR>
	 * 功能:保存图片的sd卡路径<BR>
	 * 返回值:void<BR>
	 */
	public static void savePic(Bitmap b, String strFileName) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(strFileName);
			if (null != fos) {
				b.compress(Bitmap.CompressFormat.PNG, 90, fos);
				fos.flush();
				fos.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
